package com.ruoyi.web.controller.shop.cms;

import java.util.List;
import java.util.ArrayList;
import java.awt.image.BufferedImage;
import org.springframework.ui.ModelMap;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.utils.file.FileUtils;
import javax.servlet.http.HttpServletRequest;
import com.ruoyi.shop.cms.domain.ShopMaterial;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.MimeTypeUtils;
import org.springframework.stereotype.Controller;
import com.ruoyi.common.utils.file.FileUploadUtils;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.shop.cms.service.IShopMaterialService;
import com.ruoyi.common.core.controller.BaseController;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * 商品素材Controller
 * 
 * |----------------------------------------------------------------------|
 * |favorshop [简单好用，让您喜爱的小商城]
 * |----------------------------------------------------------------------|
 * |copyright www.favorshop.cn All rights reserved.
 * |----------------------------------------------------------------------|
 * | @author xuxiang
 * |----------------------------------------------------------------------|
 * | @date 2023-05-29
 * |----------------------------------------------------------------------|
 */

@Controller
@RequestMapping("/shop/material")
public class ShopMaterialController extends BaseController {
	private String prefix = "shop/cms/material";

	@Autowired
	private IShopMaterialService shopMaterialService;

	@RequiresPermissions("shop:material:view")
	@GetMapping()
	public String material() {
		return prefix + "/material";
	}

	/**
	 * 查询商品素材列表
	 */
	@PostMapping("/list")
	@ResponseBody
	public TableDataInfo list(ShopMaterial material) {
		startPage();
		List<ShopMaterial> list = shopMaterialService.selectMaterialList(material);
		return getDataTable(list);
	}

	/**
	 * 上传单个素材文件
	 * 
	 * @param file
	 * @return
	 * @throws Exception
	 */
	@PostMapping("/uploadMaterial")
	@ResponseBody
	public AjaxResult uploadMaterial(MultipartFile file) throws Exception {
		try {
			// 上传并返回新文件名称
			String filePath = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
			AjaxResult ajax = AjaxResult.success();
			ajax.put("url", filePath);
			ajax.put("size", file.getSize());
			ajax.put("extension", FileUploadUtils.getExtension(file));
			ajax.put("width", getImgWidth(file));
			ajax.put("height", getImgHeight(file));
			ajax.put("newFileName", FileUtils.getName(filePath));
			ajax.put("originalFilename", file.getOriginalFilename());
			return ajax;
		} catch (Exception e) {
			return AjaxResult.error(e.getMessage());
		}
	}

	/**
	 * 批量上传素材
	 */
	@Log(title = "批量上传素材", businessType = BusinessType.INSERT)
	@PostMapping("/uploadMaterials")
	@ResponseBody
	public AjaxResult uploadMaterials(HttpServletRequest request, MultipartFile[] files, Long groupId) {
		List<ShopMaterial> materials = new ArrayList<ShopMaterial>();
		try {
			for (MultipartFile file : files) {
				// 上传并返回新文件名称
				String fileName = FileUploadUtils.upload(RuoYiConfig.getUploadPath(), file);
				ShopMaterial material = new ShopMaterial();
				material.setMaterialName(file.getOriginalFilename());
				material.setMaterialType(1);
				material.setGroupId(groupId);
				material.setSize(file.getSize());
				material.setUrl(fileName);
				material.setExtension(FileUploadUtils.getExtension(file));
				material.setCreateBy(this.getLoginName());
				material.setCreateTime(DateUtils.getNowDate());
				material.setWidth(getImgWidth(file));
				material.setHeight(getImgHeight(file));
				material.setExtension( FileUploadUtils.getExtension(file));
				materials.add(material);
			}
			return toAjax(shopMaterialService.insertMaterials(materials));
		} catch (Exception e) {
			logger.error("操作失败", e);
			return AjaxResult.error(e.getMessage());
		}
	}

	/**
	 * 修改素材
	 */
	@RequiresPermissions("shop:material:edit")
	@GetMapping("/edit/{materialId}")
	public String edit(@PathVariable("materialId") Long materialId, ModelMap mmap) {
		ShopMaterial shopMaterial = shopMaterialService.selectMaterialById(materialId);
		mmap.put("material", shopMaterial);
		return prefix + "/edit";
	}

	/**
	 * 修改保存素材
	 */
	@RequiresPermissions("shop:material:edit")
	@Log(title = "素材", businessType = BusinessType.UPDATE)
	@PostMapping("/edit")
	@ResponseBody
	public AjaxResult editSave(ShopMaterial material) {
		material.setUpdateBy(getLoginName());
		return toAjax(shopMaterialService.updateMaterial(material));
	}

	/**
	 * 批量删除素材
	 */
	@RequiresPermissions("system:material:remove")
	@Log(title = "商品素材", businessType = BusinessType.DELETE)
	@GetMapping("/remove/{materialIds}")
	@ResponseBody
	public AjaxResult remove(@PathVariable("materialIds") String materialIds) {
		return toAjax(shopMaterialService.deleteByMaterialIds(materialIds));
	}

	/**
	 * 批量修改素材分组
	 */
	@Log(title = "修改素材分组", businessType = BusinessType.UPDATE)
	@PostMapping("/changeGroup")
	@ResponseBody
	public AjaxResult changeGroup(String materialIds, Long groupId) {
		return toAjax(shopMaterialService.changeGroup(materialIds, groupId));
	}

	/**
	 * 批量选择素材
	 * 
	 * @param mmap
	 * @return
	 */
	@GetMapping("/selectMultiMaterial")
	public String selectMultiMaterial(ModelMap mmap) {
		return prefix + "/materialMulti";
	}

	/**
	 * 获取图片宽度
	 * 
	 * @param file 图片文件
	 * @return 宽度
	 */
	public static int getImgWidth(MultipartFile file) {
		String suffix = FileUploadUtils.getExtension(file);
		if (!isImage(suffix)) {
			return 0;
		}
		BufferedImage src = null;
		int ret = -1;
		try {
			src = javax.imageio.ImageIO.read(file.getInputStream());
			ret = src.getWidth(null); // 得到源图宽
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	/**
	 * 获取图片高度
	 * 
	 * @param file 图片文件
	 * @return 高度
	 */
	public static int getImgHeight(MultipartFile file) {
		String suffix = FileUploadUtils.getExtension(file);
		if (!isImage(suffix)) {
			return 0;
		}
		BufferedImage src = null;
		int ret = -1;
		try {
			src = javax.imageio.ImageIO.read(file.getInputStream());
			ret = src.getHeight(null); // 得到源图高
		} catch (Exception e) {
			e.printStackTrace();
		}
		return ret;
	}

	/**
	 * 是否图片
	 * 
	 * @param suffix
	 * @return
	 */
	public static final boolean isImage(String extension) {
		for (String str : MimeTypeUtils.IMAGE_EXTENSION) {
			if (str.equalsIgnoreCase(extension)) {
				return true;
			}
		}
		return false;
	}

}
